package com.community.manage.listener;

import com.alibaba.fastjson.JSONObject;
import com.community.common.entity.GroupGood;
import com.community.common.entity.vo.SendSmsParamVo;
import com.community.common.utils.StringUtils;
import com.community.manage.entity.vo.GroupGoodVo;
import com.community.manage.service.ManageService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Log4j2
public class RabbitMqListener {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    ManageService manageService;


    /**
     * 初始化延迟队列
     * @return
     */
    @Bean
    public Queue initReleaseQueue() {
        return new Queue("group-release-queue",true);
    }

    /**
     * 监听队列
     * @param msg
     * @param message
     * @param channel
     */
    @RabbitListener(queues = "group-release-queue")
    public void  secondQueue(String msg, Message message, Channel channel) {

        log.info("msg->【{}】",msg);
        // 消息唯一标识tag
        MessageProperties messageProperties = message.getMessageProperties();
        try {
            GroupGoodVo groupGoodVo = JSONObject.parseObject(msg, GroupGoodVo.class);

            // 此消息的唯一消息键
            String msgId = (String) redisTemplate.opsForValue().get("sms_msgId_" + groupGoodVo.getMsgId());
            // 已消费
            if(StringUtils.isNotEmpty(msgId)) {
                // 手动签收，不重回队列
                channel.basicAck(messageProperties.getDeliveryTag(),false);
                return;
            }
            // 查找拼团商品
            GroupGood groupGood = manageService.findGroupGood(groupGoodVo.getId());
            // 过期未完成
            if(groupGood.getStatus() ==0) {
                manageService.updateGroupGoodStatus(groupGoodVo.getId());
            }

            // 手动签收，不重回队列
            channel.basicAck(messageProperties.getDeliveryTag(),false);
            redisTemplate.opsForValue().set("sms_msgId_"+groupGoodVo.getMsgId(),groupGoodVo.getMsgId(),6, TimeUnit.HOURS);
        } catch (IOException e) {
            try {
                // 确认没签收，重回队列
                channel.basicNack(messageProperties.getDeliveryTag(),false,true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
        }

    }
}
